package com.atguigu.gulimall.gulimallgateway;
import java.util.LinkedList;

public class ThreadPool {
    private int threadPoolSize = 10;  //线程池的默认大小
    private LinkedList<Runnable> linkedList = new LinkedList<>();   //用于存放提交到线程池的任务

    public ThreadPool(int threadPoolSize) {
        if (threadPoolSize > 0)
            this.threadPoolSize = threadPoolSize;
        //启动线程
        synchronized (linkedList) {
            for (int i = 0; i < this.threadPoolSize; i++) {
                new MyThread("线程-->" + i).start();
            }
        }
    }

    public void add(Runnable runnable) {
        synchronized (linkedList) {
            linkedList.add(runnable);
            linkedList.notifyAll();
        }
    }

    class MyThread extends Thread {
        Runnable task = null;

        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println(this.getName() + ",启动了");
            while (true) {
                //不断从任务队列中检查是否有任务需要进行
                synchronized (linkedList) {
                    while (linkedList.isEmpty()) {
                        try {
                            linkedList.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    task = linkedList.removeFirst();
                }
                task.run();
                System.out.println(this.getName() + ",得到执行");
            }


        }
    }

    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(20);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        for (int i = 0; i < 20; i++) {
            threadPool.add(runnable);
        }
    }
}